<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\result\Result;
use app\model\Category;
use app\model\Product as ModelProduct;
use think\facade\Request;

/**
 *
 */
class Product extends BaseController
{

    /**
     * @var string[]
     */
    protected $middleware = [
        'auth',
        'checkPermission'
    ];

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $pageNum = Request::param('pageNum');
        $pageSize = Request::param('pageSize');
        $categoryId = Request::param('categoryId');
        $map = [];

        if (isset($categoryId)) {
            $map['category_id'] = $categoryId;
        }

        $roleList = ModelProduct::with('category')->where($map)->page($pageNum, $pageSize)->order('sort', 'desc')->select();
        return Result::Success($roleList);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $name = Request::post('name');
        $image = Request::post('image');
        $sort = Request::post('sort');
        $keywords = Request::post('keywords');
        $description = Request::post('description');
        $categoryId = Request::post('categoryId');

        $hasRole = ModelProduct::where('name', $name)->findOrEmpty();

        if ($hasRole->isEmpty()) {

            $product = new ModelProduct();
            $product->name = $name;
            $product->image = $image;
            $product->sort = $sort;
            $product->keywords = $keywords;
            $product->description = $description;
            $product->save();

            $category = Category::find($categoryId);
            $category->products()->save($product);


            return Result::Success($product);
        } else {
            return Result::Error(500, '同名商品已存在');
        }
    }
}
